<?php

namespace app\supplier\model\plus\activity;

use app\common\enum\order\OrderSourceEnum;
use app\common\model\plus\activity\Active as ActiveModel;
use app\common\model\plus\activity\Product as ActivityProductModel;
use app\common\model\plus\activity\ProductSku as ProductSkuModel;
use app\shop\model\order\Order as OrderModel;
use app\supplier\model\supplier\Supplier;

/**
 *
 */
class Active extends ActiveModel
{
    public function getList($data, $shop_supplier_id)
    {
        $supplier = (new Supplier())->find($shop_supplier_id);
        if (!$supplier || $supplier["is_recycle"] == 1 || $supplier["is_audit"] != 1) {
            $this->error = "商户不存在或异常";
            return false;
        }
        // 获取数据列表
        $model = $this;

        if (isset($data["title"]) && !empty($data["title"])) {
            $data["title"] = trim($data["title"]);
            $model = $model->where("title", 'like','%'.$data["title"].'%');
        }

        if (isset($data["status"]) && $data["status"] !== "") {
            switch ($data["status"]) {
                case 0:
                    $model = $model->where(function ($query) {
                        $query->where("start_time", ">", time());
                    });
                    break;
                case 1:
                    $model = $model->where("status", 1)->where("start_time", "<", time())->where("end_time", ">", time());
                    break;
                case 2:
                    $model = $model->where("status", 1)->where("end_time", "<", time());
                    break;
            }
        }
        $list = $model->order(['sort' => 'asc', 'create_time' => 'desc'])
//            ->where('status', '=', 1)
            ->where('is_delete', '=', 0)
            ->where("shop_supplier_id", $supplier["shop_supplier_id"])
            ->paginate($data);
            // dump($list);exit;

        foreach ($list as $active) {
            $active["can_edit"] = $active["shop_supplier_id"] == $shop_supplier_id ? 1 : 0;
        }

        return $list;
    }

    public function add($shop_supplier_id, $data)
    {
        $this->startTrans();
        try {
            //添加商品
            $stock = array_sum(array_column($data['product']['spec_list'], 'activity_stock'));
            $arr = [
                'product_id' => $data['product_id'],
                'activity_id' => $data['activity_id'],
                'app_id' => self::$app_id,
                'stock' => $stock,
                'limit_num' => $data['limit_num'],
                'position' => $data['position'],
                'shop_supplier_id' => $shop_supplier_id
            ];

            $model = new ActivityProductModel();
            $model->save($arr);
            //商品规格
            $sku_model = new ProductSkuModel();
            $sku_data = [];
            foreach ($data['product']['spec_list'] as $sku) {
                $sku_data[] = [
                    'activity_product_id' => $model['activity_product_id'],
                    'product_id' => $data['product_id'],
                    'product_sku_id' => $sku['product_sku_id'],
                    'activity_price' => $sku['activity_price'],
                    'product_price' => $sku['product_price'],
                    'activity_stock' => $sku['activity_stock'],
                    'product_attr' => isset($sku['product_attr']) ? $sku['product_attr'] : '',
                    'activity_id' => $data['activity_id'],
                    'app_id' => self::$app_id,
                ];
            }
            $sku_model->saveAll($sku_data);
            // 事务提交
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }

    public function addActive($data, $shop_supplier_id)
    {
        $supplier = (new Supplier())->find($shop_supplier_id);
        if (!$supplier || $supplier["is_recycle"] == 1 || $supplier["is_audit"] != 1) {
            $this->error = "商户不存在或异常";
            return false;
        }
        $this->startTrans();
        try {
            $arr = $this->setData($data, $supplier);
            $this->save($arr);
            // 事务提交
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }

    public function editActive($data, $shop_supplier_id)
    {
        $supplier = (new Supplier())->find($shop_supplier_id);
        if (!$supplier || $supplier["is_recycle"] == 1 || $supplier["is_audit"] != 1) {
            $this->error = "商户不存在或异常";
            return false;
        }
        $this->startTrans();
        try {
            if ($shop_supplier_id != $this["shop_supplier_id"]) {
                $this->error = "你无权修改此活动";
                $this->rollback();
                return false;
            }
            $arr = $this->setData($data, $supplier);
            $this->save($arr);
            // 事务提交
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }


    private function setData($data, $supplier)
    {
        //鉴权
        $noAuth = Supplier::checkauth($supplier['shop_supplier_id'],'active');
        $data['active_date'][0] = substr($data['active_date'][0], 0, 10);
        $data['active_date'][1] = substr($data['active_date'][1], 0, 10);
        $data['active_time'][0] = substr($data['active_time'][0], 0, 5);
        $data['active_time'][1] = substr($data['active_time'][1], 0, 5);
        $arr = [
            'shop_supplier_id' => $supplier['shop_supplier_id'],
            'image_id' => $data['image_id'],
            'imgUrl' => $data['imgUrl'],
            'title' => $data['title'],
            'status' => $data['status'],
            'identifying' => $data['identifying'],
            'label' => $data['label'],
            'is_coupon' => $data['is_coupon'],
            'sort' => $data['sort'],
            'start_time' => strtotime($data['active_date'][0] . ' ' . $data['active_time'][0] . ':00'),
            'end_time' => strtotime($data['active_date'][1] . ' ' . $data['active_time'][1] . ':59'),
            'join_end_time' => strtotime($data['join_end_time']),
            'day_start_time' => $data['active_time'][0] . ':00',
            'day_end_time' => $data['active_time'][1] . ':59',
            'app_id' => self::$app_id,
            'bgColor' => $data['bgColor'],
            'share_title' => $data['share_title'],
            'share_img' => $data['share_img']??'',
            'navbar_title' => $data['navbar_title']??'',
            'navbar_bgcolor' => $data['navbar_bgcolor']??'',
            'left_color' => $data['left_color']??'',
            'right_color' => $data['right_color']??'',

            'supplier_range' => 2,
            'province_id' => $supplier["province_id"] ?? 0,
            'city_id' => $supplier["city_id"] ?? 0,
            'county_id' => $supplier["county_id"] ?? 0,
            'proxy_id' => $supplier["proxy_id"] ?? 0,
            'is_audit' => $noAuth?1:0,
            'is_new' => $data['is_new']??0,
            'stock' => $data['stock']??0,
            'balance_stock' => $data['balance_stock']??0
        ];

        return $arr;
    }

    public function del()
    {
        // 如果有未付款订单不能删除
        $count = (new OrderModel())->where('pay_status', '=', 10)
            ->where('order_source', '=', OrderSourceEnum::SECKILL)
            ->where('activity_id', '=', $this['activity_id'])
            ->where('is_delete', '=', 0)
            ->count();
        if ($count > 0) {
            $this->error = '该活动下有未付款的订单';
            return false;
        }
        return $this->save([
            'is_delete' => 1
        ]);
    }
}